var MachineBoard = function () {
  var template = /* html */ `
    <div class="machine-board" v-loading.fullscreen.lock="loading">
      <search-btns ref="searchBtns" :pagination="pagination" :has-scroll="hasScrolling" :has-search="true" search-btn-text="查询" :popover-width="250"
        search-title="查询条件" @after-leave="afterLeave" v-if="search!==null">
        <div slot="search">
          <template v-if="deptWorkName===null">
            <el-cascader clearable filterable v-model="search.deptWork" size="small" :options="deptWorkshopList" placeholder="部门-车间" separator="-"
              :props="deptWorkProps" style="width:180px"></el-cascader>
            <el-button size="small" type="primary" @click="searchData">查询</el-button>
          </template>
          <span v-else>部门-车间：{{deptWorkName}}</span>
        </div>
      </search-btns>
      <div class="machine-board-content" :key="boardId">
        <template v-for="(machineList,rowIndex) in pageMachineList">
          <div :key="'machineRow_'+rowIndex" :style="{height:'calc('+(100/rowNum)+'% - 3px)'}">
            <template v-for="(machine,index) in machineList">
              <machine-item :machine="machine" :is-show="getHasShow(rowIndex)" :chart-start-date="showDateList[showStartDateIndex]" 
                :key="'machine_'+index"></machine-item>
            </template>
          </div>
        </template>
      </div>
    </div>
  `;

  return {
    mixins: [
      boardRunningMixin,
      boardMixin()
    ],

    watch: {
      currentRowIndex: function (newVal) {
        var $content = $(this.$el).find('.machine-board-content');
        var scrollTop = $content.scrollTop();
        var top = $content.find(`>div:eq(${newVal})`).position().top;
        scrollTop += top - 5;

        var self = this;
        this.hasScrolling = true;
        $content.animate({
          scrollTop: scrollTop
        }, 1000, function () {
          self.hasScrolling = false;
        });
      }
    },

    computed: {
      currentRowIndex: {
        get: function () {
          var pagination = this.pagination;
          var currentPage = pagination.currentPage;
          var rowIndex = (currentPage - 1) * this.rowNum;
          return rowIndex;
        },
        set: function (val) {
          var currentPage = val / this.rowNum;
          currentPage = Math.floor(currentPage);
          this.pagination.currentPage = currentPage;
        }
      }
    },

    data: function () {
      return {
        loading: false,
        boardId: SysUtil.getId(),
        search: null,
        oldSearch: null,
        machineList: [],
        searchMachineList: [],
        pageMachineList: [],
        deptWorkshopList: [],
        pagination: {
          currentPage: 1,
          totalCount: 0,
          pageSize: 6
        },
        rowNum: 2,
        colNum: 3,
        showDateList: this.getShowDateList(),
        showStartDateIndex: 0,
        hasScrolling: false,
        hasSelect: true,
        deptWorkProps: {
          checkStrictly: true,
          value: 'id',
          label: 'name',
          children: 'workshops'
        }
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      this.setUser().then(function () {
        return self.setMachineList(true).then(function (machineList) {
          return self.refreshMachineInfo(machineList).then(function (machineList) {
            self.machineList = machineList;
            self.setDeptWorkshopList();
            self.toSearchMachineList();
            self.toPageMachineList();
            self.loading = false;
            self.boardRuning();
          });
        });
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      setUser: function () {
        var self = this;
        return SysUtil.getUser().then(function (user) {
          var deptWork;
          var permissionList = user.permissionList;
          var isManager = user.isManager;
          if (permissionList.indexOf('/superManager') !== -1) {
            isManager = 1;
          }
          
          var hasSelect = isManager === 1 || user.duty === '1';
          if (hasSelect) {
            deptWork = [];
          } else {
            var deptId = user.deptId;
            if (SysUtil.isEmpty(deptId) || deptId === '0') {
              return user;
            }
            deptWork = [`dept-${deptId}`];
            var workShopId = user.workShopId;
            if (!SysUtil.isEmpty(workShopId) && workShopId !== '0') {
              deptWork.push(`workshop-${workShopId}`);
            }
          }
          var search = {
            deptWork: deptWork
          };
          self.search = _.cloneDeep(search);
          self.oldSearch = _.cloneDeep(search);
          if (hasSelect) {
            return user;
          }
          return self.setDeptWorkName(deptWork, user);
        });
      },

      getShowDateList: function () {
        var showDateList = [];
        var dateMoment = moment().subtract(29, 'day');
        var maxMoment = moment().subtract(9, 'day');
        while (maxMoment.isAfter(dateMoment)) {
          showDateList.push(dateMoment.format('YYYY-MM-DD'));
          dateMoment.add(1, 'day');
        }
        return showDateList;
      },

      setMachineList: function (hasAlert) {
        if (hasAlert === undefined) {
          hasAlert = false;
        }

        var search = this.search;
        var postData = {};
        if (search === null) {
          postData.workShop = -1;
        }
        return ajaxRequest('equipment/getEquipmentBoard', postData, true, hasAlert).then(function (machineList) {
          if (machineList === null) {
            machineList = [];
          }
          machineList = _.map(machineList, function (machine) {
            machine = new MachineInfo(machine);
            return machine;
          });
          return machineList;
        });
      },

      refreshMachineInfo: function (machineList) {
        var equipmentNoList = _.map(machineList, 'equipmentNo');
        return ajaxRequest('equipment/getDynamicEquipmentBoardData', {
          equipmentNos: JSON.stringify(equipmentNoList)
        }, true, false).then(function (machineData) {
          if (machineData === null) {
            machineData = {};
          }
          for (var i = 0; i < machineList.length; i++) {
            var machine = machineList[i];
            var data = machineData[machine.equipmentNo];
            if (data !== undefined) {
              machine.refreshData(data);
            }
          }
          return machineList;
        });
      },

      toSearchMachineList: function () {
        var machineList = this.machineList;

        var deptWork = this.deptWork;
        if (deptWork !== null) {
          machineList = _.filter(machineList, function (machine) {
            var dept = deptWork.dept;
            if (dept !== undefined) {
              if (machine.deptId !== dept) {
                return false;
              }
            }
            var workshop = deptWork.workshop;
            if (workshop !== undefined) {
              if (machine.workShopId !== workshop) {
                return false;
              }
            }
            return true;
          });
        }

        this.oldSearch = _.cloneDeep(this.search);
        this.searchMachineList = machineList;
        this.pagination.totalCount = machineList.length;
      },

      searchData: function () {
        this.loading = true;

        this.clearTimeoutList();
        var self = this;
        setTimeout(function () {
          self.$refs['searchBtns'].closePopover();
          self.toSearchMachineList();
          self.toPageMachineList();
          self.boardId = SysUtil.getId();
          self.boardRuning();
          self.loading = false;
        }, 500);
      },

      toPageMachineList: function () {
        var machineList = this.searchMachineList;
        var pageMachines = [];
        var colNum = this.colNum;
        var rowNum = this.rowNum;
        var totalRow = machineList.length / colNum;
        totalRow = _.round(totalRow, 1);
        totalRow = Math.ceil(totalRow / rowNum) * rowNum;

        for (var i = 0; i < totalRow; i++) {
          pageMachines.push([]);
        }

        var lastRow = 0;
        for (var i = 0; i < machineList.length; i++) {
          var machine = machineList[i];
          var rowIndex = i / colNum;
          rowIndex = Math.floor(rowIndex);
          pageMachines[rowIndex].push(machine);
          if (i === machineList.length - 1) {
            lastRow = rowIndex;
          }
        }

        var lastMachine = pageMachines[lastRow];
        if (lastMachine && lastMachine.length > 0) {
          for (var i = lastMachine.length; i < colNum; i++) {
            lastMachine.push(null);
          }
        }

        this.pageMachineList = pageMachines;
      },

      afterLeave: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },

      getHasShow: function (rowIndex) {
        var rowNum = this.rowNum;
        var currentRowIndex = this.currentRowIndex;
        if (rowIndex >= currentRowIndex && rowIndex <= currentRowIndex + rowNum - 1) {
          return true;
        }
        return false;
      },

      setDeptWorkshopList: function () {
        var machineList = this.machineList;
        var len = machineList.length;
        var deptWorkshopMap = {};
        for (var i = 0; i < len; i++) {
          var machine = machineList[i];
          var deptId = machine.deptId;
          if (SysUtil.isEmpty(deptId) || deptId === '0') {
            continue;
          }
          var deptWorkshop = deptWorkshopMap[deptId];
          if (deptWorkshop === undefined) {
            deptWorkshop = {
              id: `dept-${deptId}`,
              name: machine.deptName,
              workshops: []
            };
            deptWorkshopMap[deptId] = deptWorkshop;
          }

          var workShopId = machine.workShopId;
          if (SysUtil.isEmpty(workShopId) || workShopId === '0') {
            continue;
          }
          deptWorkshop.workshops.push({
            id: `workshop-${workShopId}`,
            name: machine.workShopName
          });
        }

        var deptWorkshopList = [];
        for (var deptId in deptWorkshopMap) {
          var deptWorkshop = deptWorkshopMap[deptId];
          deptWorkshop.workshops = _.uniqBy(deptWorkshop.workshops, 'id');
          deptWorkshopList.push(deptWorkshop);
        }
        this.deptWorkshopList = deptWorkshopList;
      },

      boardRuning: function () {
        this.clearTimeoutList();
        this.setMachineDataRuning();
        this.resetMachineInfoRuning();
        this.resetMachineListRuning();
      },

      setMachineDataRuning: function () {
        var self = this;
        var timeout = setTimeout(function () {
          var showStartDateIndex = self.showStartDateIndex;
          var showDateList = self.showDateList;
          if (showDateList.length === 0) {
            self.showStartDateIndex = 0;
            return;
          }
          var index = (showStartDateIndex + 1) % showDateList.length;
          self.showStartDateIndex = index;
          self.timeoutList[0] = null;
          self.setMachineDataRuning();
        }, 5000);
        this.timeoutList[0] = timeout;
      },

      resetMachineInfoRuning: function () {
        var self = this;
        var timeout = setTimeout(function () {
          var machineList = self.machineList;
          self.refreshMachineInfo(machineList).then(function () {
            self.resetMachineInfoRuning();
          });
          self.timeoutList[1] = null;
        }, 5000);
        this.timeoutList[1] = timeout;
      },

      resetMachineListRuning: function () {
        var tomorrowMoment = moment().add(1, 'day').startOf('day').set({
          hour: 1
        });
        var delayTime = tomorrowMoment.diff(moment());

        var self = this;
        var timeout = setTimeout(function () {
          self.setMachineList().then(function (machineList) {
            self.refreshMachineInfo(machineList).then(function (machineList) {
              self.machineList = machineList;
              self.setDeptWorkshopList();
              self.toSearchMachineList();
              self.toPageMachineList();
              self.boardId = SysUtil.getId();
              self.showDateList = self.getShowDateList();
              self.resetMachineListRuning();
            });
          });
          self.timeoutList[2] = null;
        }, delayTime);
        this.timeoutList[2] = timeout;
      }
    },

    components: {
      SearchBtns: SearchBtns,
      MachineItem: MachineItem
    },

    template: template
  };
}();
